<template>
    <div class="LivevideoRoom">
        <Head></Head>
        <div class="LivevideoRoom-con">
            <div class="LivevideoRoom-content">
                <div class="LivevideoRoom-head">
                    <div class="head-left">
                        <label>{{group_name}}</label>
                        <label>
                            <span>{{groupinfo.language}}</span>
                            <span>{{groupinfo.map.userinfo.nick_name}}老师</span>
                        </label>
                    </div>
                    <div class="head-right">
                        <label>
                            <span>正在直播 00:12:26</span>
                        </label>
                        <label>
                            <span>当前在线({{ChatNav[0].OnlineNmuver}})</span>
                        </label>
                        <label class="oicebroadcast-info-right">
                            <span  @click="Exitto">退出直播间</span>
                        </label>
                    </div>
                </div>
                <div>
                    <div class="LivevideoRoom-left">
                        <div id="video_test">
                            <span v-if="Istart == 1" @click="Getpush()">获取推流地址</span>
                            <span v-else-if="Istart ==2" @click="Tostrt()">开播</span>
                            <span v-else-if="Istart ==3" style="display:none"></span>
                        </div>
                        <div class="video-footer">
                            <img src="/images/矩形 32@2x.png" alt="">
                            <img src="/images/矩形 33@2x (1).png" alt="">
                        </div>
                    </div>
                    <div class="LivevideoRoom-right">
                        <div class="classinfos" @mouseleave="tolive()" v-show="Informations">
                            <span class="iconfos"></span>
                            <div>
                                <label>
                                    <img src="/images/加好友icon@2x.png" alt="">
                                    <span style="color:#32CBD5">加好友</span>
                                </label>
                                <label class="classinfos-avater">
                                    <img :src="InformationsImg" alt="">
                                    <span>{{Informationsnick}}</span>
                                </label>
                                <label>
                                    <img src="/images/送礼物.png" alt="">
                                    <span style="color:#FF3DAB">送礼物</span>
                                </label>
                            </div>
                            <div>
                                <label>
                                    <img src="/images/个人主页icon@2x.png" alt="">
                                    <span>个人主页</span>
                                </label>
                                <label>
                                    <img src="/images/直播讲师详情icon@2x.png" alt="">
                                    <span>直播讲师详情</span>
                                </label>
                                <label>
                                    <img src="/images/助学师详情icon@2x.png" alt="">
                                    <span>助学师详情</span>
                                </label>
                            </div>
                        </div>
                        <div class="LivevideoRoom-right-head">
                            <ul>
                                <li v-for="(Navitem,Navindex) in ChatNav" :key="Navindex" :class="ChatNavindex == Navindex?'navsed':''" @click="Tonav(Navindex)">
                                    {{Navitem.name}}({{Navitem.OnlineNmuver}})
                                </li>
                            </ul>
                            <div class="LivevideoRoom-right-head-lsit">
                                <!-- <div v-if="ChatNavindex ==0">
                                    <div v-if="wheatinformation.length == 0" class="Nodata">
                                        <img src="/images/暂无数据.png" alt="">
                                        <span>暂无学员</span>
                                    </div>
                                    <ul v-else>
                                        <li v-for="(wheatitem,wheatindex) in wheatinformation" :key="wheatindex">
                                            <label>
                                                <img :src="wheatitem.userAvatar" alt="">
                                                <span>{{wheatitem.userName}}</span>
                                            </label>
                                            <label>
                                                <span @click="kicking(wheatitem)">下麦</span>
                                            </label>
                                        </li>
                                    </ul>
                                </div>
                                <div v-else-if="ChatNavindex == 1">
                                    <div v-if="wheatlist.length == 0" class="Nodata">
                                        <img src="/images/暂无数据.png" alt="">
                                        <span>暂无待麦人员</span>
                                    </div>
                                    <ul class="Tomak" v-else>
                                        <li v-for="(tomakitem,tomeakindex) in wheatlist" :key="tomeakindex"> 
                                            <label>
                                                <img :src="tomakitem.userAvatar" alt="">
                                                <span>{{tomakitem.userName}}</span>
                                            </label>
                                            <label>
                                                <img @click="invitationwheet(tomakitem,tomeakindex)" src="/images/接受.png" alt="">
                                                <img @click="todelete(tomeakindex)" src="/images/拒绝.png" alt="">
                                                <img @click="Placedtop(tomakitem,tomeakindex)" src="/images/置顶.png" alt="">
                                            </label> 
                                        </li>
                                    </ul>
                                </div> -->
                                <div v-if="ChatNavindex == 0" ref="nas1" class="nas1" v-bind:style="{height: widthData,overflow:Overflowdata}" @mouseover="toan" @mouseleave="outan">
                                    <div class="nas2">
                                        <div class="nas3">
                                            <div class="nas4">
                                            <ul class="onlineitem">
                                                <li v-for="(onlineitem,onlineindex) in numberofonline" :key="onlineindex">
                                                    <label >
                                                        <img @click="Indusinfo(onlineitem)" :src="onlineitem.map.userinfo.avatar" alt="" style="cursor: pointer;">
                                                        <span>{{onlineitem.map.userinfo.nick_name}}</span>
                                                    </label>
                                                    <label>
                                                        <label v-if="onlineitem.status==1" class="online">
                                                            <span @click="invitationwheets(onlineitem)">邀请</span>
                                                            <span >在线</span>
                                                        </label>
                                                        <label class="outline" v-else>
                                                            <span>离线</span>
                                                        </label>
                                                        
                                                    </label>
                                                </li>
                                            </ul>
                                            </div>
                                        </div>
                                    </div>
                                    
                                </div>
                                
                            </div>
                        </div>
                        
                        <div class="LivevideoRoom-right-content">
                            <div class="Systemmessage">
                                <p>系统消息：</p>
                                <p>欢迎来到直播间！Tmore提倡绿色健康直播。直播内容和评论内容严禁出现违法、违规、低俗色情、吸烟汹酒等内容，如有违反，将视情节严重程度对作者账号进行处罚。</p>
                            </div>
                            <div class="MessageList" id="MessageList">
                                <ul >
                                <li v-for="(messageitem,messindex) in ThemessageList" :key="messindex">
                                    <span v-if="messageitem[0].nick == 0">啊哈哈</span>
                                    <span v-else>{{messageitem[0].nick}}:</span>
                                    
                                    <span>{{messageitem[0].msg}}</span>
                                </li>
                                </ul>
                            </div>
                            
                            <div class="messagefooter">
                                <label></label>
                                <div>
                                    <textarea v-model="thetex" @keydown.enter="Tochat" name="" id=""></textarea>
                                    <span @click="Tochat">发送</span>
                                </div>
                                
                            </div>
                        </div>
                    </div>
                </div>
                <div class="videolist" style="display: none;">
                    <div v-for="(rooitem,roomindex) in roomdis" :key="roomindex" v-bind:id="rooitem.Id" :class="rooitem.Id" class="videsu">
                        <!-- {{rooitem}} -->
                    </div>
                </div>
            </div>
            <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose">
                <span>{{toconname}}请求连麦</span>
                <span slot="footer" class="dialog-footer">
                    <el-button style="width:30%" @click="Refusedto">拒绝</el-button>
                    <el-button type="primary" style="width:30%" @click="toallowed">确 定</el-button>
                </span>
            </el-dialog>
        </div>
        <Modal :show="show" :Theserver="Theserver" :Thekeys="Thekeys" :title="title" @hideModal="hideModal" @submit="submit">
            <span slot="Solt1" data-clipboard-text="Theserver" id="copys"> 
                OBS推流服务器：{{Theserver}}
            </span>
            <span slot="Solt2">
                OBS推流密钥：{{Thekeys}}
            </span>
        </Modal >
        <Footer></Footer>
    </div>
</template>
<script>
import TIM from 'tim-js-sdk';
let options = {
  SDKAppID: 1400255047 // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
};
import Head from '../../components/LiverHead'
import {TimLogin} from '../../components/Tim'
import Footer from '../../components/footer'
import $ from 'jquery';
import Modal  from '../Voicebroadcast/Dialog'
export default {
    name:'LivevideoRoom',
    data(){
        return{
            groupinfo:'',//上一个页面传来的房间信息

            //聊天框导航
            ChatNav:[
                // {
                //     name:'台上',
                //     OnlineNmuver:0,
                // },
                // {
                //     name:'待麦',
                //     OnlineNmuver:0,
                // },
                {
                    name:'在线',
                    OnlineNmuver:0,
                }
            ],
            ChatNavindex:0,
            thetex:'',
            Istart:1,
            unserinfo:JSON.parse(localStorage.getItem('userinfo')),
            wheatinformation:[],

            //弹窗信息
            title: 'obs推流地址',
            show: false,
            Theserver:'',//obs推流服务器地址
            Thekeys:'',//obs密钥地址

            numberofonline:[],//在线人数
            Informations:false,
            InformationsImg:'',
            Informationsnick:'',    

            //收到的消息信息
            ThemessageList:[],
            conversationID:'',
            widthData:'150px',
            Overflowdata:'hidden',

            tim : TIM.create(options),

            //收到连麦请求
            dialogVisible:false,
            toconname:'',
            toids:'',
            bigAnchorStreamID:'',

            //定时器相关
            heartds:'',
            RoomInfoos:[],
            wheatlist:[],

            roomdis:[],
            screenWidth: document.body.clientWidth,
            isscenario:'',
            group_id:'',
            group_ids:'',
            group_name:'',
            faceUrl:'',
            isfasong:true,
        }
    },
    updated(){
        // 聊天定位到底部
          let ele = document.getElementById('MessageList');
          ele.scrollTop = ele.scrollHeight;
    },
    mounted(){
        var _this = this
        _this.groupinfo = JSON.parse(_this.$route.query.item);
        _this.isscenario = _this.$route.query.isscenario
        if(this.isscenario){
            _this.conversationID = "GROUP"+_this.groupinfo.group_id
            _this.group_id = _this.groupinfo.id
            _this.group_ids = _this.groupinfo.group_id
            _this.group_name = _this.groupinfo.group_name
            _this.faceUrl = _this.groupinfo.faceUrl
        }else{
            _this.conversationID = "GROUP"+_this.groupinfo.map.groupinfo.group_id
            _this.group_id = _this.groupinfo.map.groupinfo.id
            _this.group_ids = _this.groupinfo.map.groupinfo.group_id
            _this.group_name = _this.groupinfo.map.groupinfo.group_name
            _this.faceUrl = _this.groupinfo.map.groupinfo.faceUrl
        }
        
        console.log(_this.groupinfo,'直播间信息')
        setTimeout(function () {//延迟2s执行IM的获取消息等功能防止sdk报错
            _this.GethistoryMessage()
            _this.GetOnMessage()
        },3000);
        TimLogin()
        _this.Getonline()
    },
    methods:{
        Indusinfo(item){//查看人员详情
            this.InformationsImg = item.map.userinfo.avatar
            this.Informationsnick = item.map.userinfo.nick_name
            this.Informations = true
        },
        tolive(){
            this.Informations = false
        },
        Getonline(){//获取在线人数列表以及在线人数数量
            var data ={
                group_id :this.group_id,
                pageSize:30,
            }
            this.$axios({
                method:'GET',
                url:'http://101.37.66.151:8768/eg-api/message/messageJoinGroup/queryOnlineCount',
                params:data,
            }).then((res) =>{
                this.numberofonline = res.data.data.messageJoinGroupEntities
                this.ChatNav[0].OnlineNmuver = res.data.data.onlineCount
            }).catch((error) =>{
                console.log(error)
            })
        },
        toan(){
            this.widthData ='260px'
            this.Overflowdata = 'auto'
        },
        outan(){
            this.widthData ='120px'
            this.Overflowdata = "hidden"
        },
        Tochat(event){
            var _this = this
            if(_this.isfasong){
                _this.isfasong = false
                event.preventDefault();
                _this.thetex = _this.thetex.split(" ").join("");
                if(_this.thetex .length== 0){
                    _this.$message({
                        message: '不能发送空消息',
                        type: 'warning'
                    });
                    _this.isfasong = true
                }else{
                    var data ={
                            cmd:'CustomCmdMsg',
                            data:{
                                cmd:'1',
                                msg:_this.thetex,
                            },
                        userName:_this.unserinfo.nick_name
                    }
                    let message = _this.tim.createCustomMessage({
                        to: _this.group_ids,
                        conversationType: TIM.TYPES.CONV_GROUP,
                        payload: {
                            text: _this.thetex,
                            data:JSON.stringify(data)
                        }
                    });
                    let promise = _this.tim.sendMessage(message);
                    promise.then(function(imResponse) {// 发送成功
                        _this.thetex =''
                        _this.isfasong = true
                        var as = [imResponse.data.message]
                        as.forEach(e=>{
                            var payload = JSON.parse(e.payload.data) 
                            var arrs = [
                                {
                                    nick:_this.unserinfo.nick_name,
                                    msg:payload.data.msg
                                }
                            ]
                            _this.ThemessageList.push(arrs)
                        })
                    }).catch(function(imError) {//发送失败
                    });
                }
            }
            
        },
        GethistoryMessage(){
            var _this = this
            // 打开某个会话时，第一次拉取消息列表
            let promise = _this.tim.getMessageList({conversationID:_this.conversationID, count: 10});
            promise.then(function(imResponse) {
                const messageListss = imResponse.data.messageList; // 消息列表。
                messageListss.forEach(e=>{
                    var payload = e.payload
                    if(payload.description ==''){
                        var payloads = JSON.parse(e.payload.data) 
                        var arrs = [{
                            nick:payloads.userName,
                            msg:payloads.data.msg
                        }]
                        _this.ThemessageList.push(arrs)
                    }
                })
            });
            
        },
        GetOnMessage(){
            var _this = this
            let onMessageReceived = function(event) {
                event.data.forEach(e => {
                    var payload = JSON.parse(e.payload.data) 
                    if(payload.cmd == 'linkmic'){
                        // if(_this.groupinfo.connect_peoplenum>_this.ChatNav[0].OnlineNmuver){
                        //     if(payload.data.roomID == _this.groupinfo.map.groupinfo.group_id){
                        //         _this.dialogVisible = true
                        //         _this.toconname = payload.data.userName
                        //         _this.toids = payload.data.userID
                        //     }
                        // }else{
                        //     if(payload.data.roomID == _this.groupinfo.map.groupinfo.group_id){
                        //         if(_this.wheatlist.length !=0){                                  
                        //             _this.wheatlist.forEach(e=>{
                        //                 if(e.userID ==  payload.data.userID){
                        //                 }else{
                        //                     _this.wheatlist.push(payload.data)
                        //                     var hash = {};
                        //                      _this.wheatlist =  _this.wheatlist.reduce(function(item, next) {
                        //                         hash[next.userID] ? '' : hash[next.userID] = true && item.push(next);
                        //                         return item
                        //                     }, [])
                        //                     _this.ChatNav[1].OnlineNmuver = _this.wheatlist.length
                        //                 }
                        //             })
                        //         }else{
                        //             _this.wheatlist.push(payload.data)
                        //             _this.ChatNav[1].OnlineNmuver = _this.wheatlist.length
                        //         }
                        //         _this.toconname = payload.data.userName
                        //         _this.toids = payload.data.userID
                        //         _this.Refusedto()
                        //     }
                        // }                       
                    }else if(payload.cmd == 'CustomCmdMsg'){
                        if(e.to == _this.group_ids){
                            var arrs = [{
                                nick:payload.userName,
                                msg:payload.data.msg
                            }]
                            _this.ThemessageList.push(arrs)
                        } 
                    }
                   
                });
                _this.Getonline()
            };
            _this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
        },
        Tonav(e){
            this.ChatNavindex = e
            if(this.ChatNavindex ==2){
                this.Getonline()
            }
        },
        Exitto(){
            this.$router.go(-1)
            clearInterval(this.time)
            this.hour =0
            this.minute =0
            this.ms =0
            this.second =0
            this.str ='00:00:00'
        },
        hideModal() {
            // 取消弹窗回调
            this.show = false
        },
        submit() {
            // 确认弹窗回调
            this.show = false
        },
        Getpush(){
            var data ={
                userID:this.unserinfo.user_id,
                roomID:this.group_ids,
                token:localStorage.getItem('token')
            }
            this.$axios({
                method:'post',
                url:'https://liveroom.qcloud.com/weapp/live_room/get_anchor_url',
                params:data,
                data: {
                    userID:this.unserinfo.user_id,
                    roomID:this.group_ids,
                },
            }).then((res) =>{
                this.Theserver =res.data.pushURL.substring(0,39)
                this.Thekeys = res.data.pushURL.substring(40,200)
                // this.Thekeys = this.Thekeys.substr(0, 3) + '****' + this.Thekeys.substr(7)
                // `${this.Thekeys.substring(0,3)}****${this.Thekeys.substring(this.Thekeys.length-3)}`
                this.pushURL = res.data.pushURL
                this.show = true
                this.Istart = '2'
                this.TocreatRoom()
            }).catch((error) =>{
                console.log(error)
            })
        },
        TocreatRoom(){
            var createRoomInfo = {
                userID: this.unserinfo.user_id,
		        roomInfo: {
                    roomID:this.group_ids,
                    pushURL: this.pushURL,
                    roomInfo:this.group_name
                },
                token:localStorage.getItem('token')
            }
            this.$axios({
                method:'post',
                url:'https://liveroom.qcloud.com/weapp/live_room/create_room',
                params:createRoomInfo,
                data: {
                    userID:this.unserinfo.user_id,
                    roomID:this.group_ids,   
                },              
            }).then((res) =>{
                if(res.data.message == "Success!"){
                    var td = {
                        roomID: this.group_ids,
                        userID: this.unserinfo.user_id,
                        userName: this.unserinfo.nick_name,
                        userAvatar:this.unserinfo.avatar,
                        pushURL: this.pushURL,
                        token:localStorage.getItem('token')
                    }
                    this.$axios({
                        method:'post',
                        url:'https://liveroom.qcloud.com/weapp/live_room/add_anchor',
                        params:td,
                        data: td,              
                    }).then((res) =>{
                        TimLogin()
                        var roominfos = {
                            roomID : this.group_ids,
                            userID: this.unserinfo.user_id,
                            token:localStorage.getItem('token')
                        }
                        this.$axios({
                            method:'post',
                            url:'https://liveroom.qcloud.com/weapp/live_room/get_anchors',
                            params:roominfos,
                            data: roominfos,              
                        }).then((res) =>{
                            this.RoomInfoos= res.data
                            this.Gethears(res.data)
                        }).catch((error) =>{
                            console.log(error)
                        })
                    }).catch((error) =>{
                        console.log(error)
                    })
                }
            }).catch((error) =>{
                console.log(error)
            })
        },
        Tostrt(){
            var _this = this
            var data = {
                userID:_this.unserinfo.user_id,
                token:localStorage.getItem('token'),
            }
            _this.$axios({
                method:'post',
                url:'https://liveroom.qcloud.com/weapp/live_room/get_room_list',
                params:data,
                data: {cnt:10},              
            }).then((res) =>{
                res.data.rooms.forEach(e=>{
                    if(e.roomID == _this.group_ids){
                        var mixedPlayURL = e.mixedPlayURL
                        console.log(e,'000')
                        mixedPlayURL = mixedPlayURL.replace('flv', "m3u8")
                        var player = new TcPlayer('video_test', {
                            m3u8: mixedPlayURL,
                            flv: e.mixedPlayURL,
                            autoplay:true,
                            muted:true,
                            width:'1000',
                            height:'553',
                            live:true,
                            h5_flv:true,
                            listener:function(msg){
                                // console.log(msg.type,'88777')
                                if(msg.type == 'play'){
                                    _this.Istart = '3'
                                    _this.Modifylivebroadcaststatus()
                                    _this.player.mute(true)
                                }else if(msg.type == 'error'){
                                    // _this.time =setInterval(this.timer,50)
                                    // _this.player.dispose()
                                    // clearInterval(this.time)
                                    // this.hour =0
                                    // this.minute =0
                                    // this.ms =0
                                    // this.second =0
                                    // this.str ='00:00:00'
                                    alert("开播失败请确认obs是否推流正确")
                                }
                            }
                        });  
                    }
                })
                
            }).catch((error) =>{
                console.log(error)
            })
        },
        Modifylivebroadcaststatus(){//修改直播状态
            var data ={
                owner_id:this.unserinfo.user_id,
                id:this.group_id,
                status:1
            }
            this.$axios({
                method:'post',
                url:'http://101.37.66.151:8768/eg-api/message/messageGroup/updateClassBeginsStatus',
                data: data,
            }).then((res) =>{
                this.timeStart()
            }).catch((error) =>{
            })
        },
        //处理连麦请求
        handleClose(done) {
            this.$confirm('确认关闭？').then(_ => {
                done();
            }).catch(_ => {});
        },
        toallowed(){
            var _this = this
            var mTimeDiff = 0;
            var data ={
                cmd:'linkmic',                   
                data:{
                    joinIndex:'',
                    roomID:_this.group_ids,
                    type:'response',
                    result: 'accept',
                    timestamp: Math.round(Date.now()) - mTimeDiff,
                    userID:_this.unserinfo.user_id,
                    userName:_this.unserinfo.nick_name,
                    userAvatar:_this.unserinfo.avatar,
                    reason: '',
                },
            }
            let message = _this.tim.createCustomMessage({
                to: _this.toids,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    data:JSON.stringify(data)
                }
            });
            let promise = _this.tim.sendMessage(message);
            promise.then(function(imResponse) {// 发送成功
                _this.dialogVisible = false
                _this.Toheart()
            }).catch(function(imError) {//发送失败
                console.log(imError,'999')
            });
        },
        Refusedto(){//拒绝连麦
            var _this = this
            var mTimeDiff = 0;
            var data ={
                cmd:'linkmic',                   
                data:{
                    joinIndex:'',
                    roomID:_this.group_ids,
                    type:'response',
                    result: 'reject',
                    reason:'主播拒绝了您的连麦请求',
                    timestamp: Math.round(Date.now()) - mTimeDiff,
                    userID:_this.unserinfo.user_id,
                    userName:_this.unserinfo.nick_name,
                    userAvatar:_this.unserinfo.avatar,
                },
            }
            let message = _this.tim.createCustomMessage({
                to: _this.toids,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    data:JSON.stringify(data)
                }
            });
            let promise = _this.tim.sendMessage(message);
            promise.then(function(imResponse) {// 发送成功
                console.log(imResponse,'000')
                _this.dialogVisible = false
                // _this.Toheart()
            }).catch(function(imError) {//发送失败
                console.log(imError,'999')
            });
        },
        //房间心跳功能，检测其混流
        Toheart(){
            this.heartds = setInterval(this.Heatr,7000)
        },
        Heatr(){//心跳开始
            var data ={
                roomID:this.group_ids,
                userID:this.unserinfo.user_id,
                roomStatusCode:'',
                token:localStorage.getItem('token')
            }
            this.$axios({
                method:'post',
                url:'https://liveroom.qcloud.com/weapp/live_room/anchor_heartbeat',
                params:data,
                data: data,              
            }).then((res) =>{
                console.log(res.data,'房间成功')
                if(res.data.code){
                    console.log('心跳失败')
                }else if(res.data.pushers){
                    console.log(res.data.pushers,'房间主播ss信息')
                    this.wheatinformation = []
                    // this.ChatNav[0].OnlineNmuver =0
                    res.data.pushers.forEach(e=>{
                        if(e.userID == this.unserinfo.user_id){

                        }else{
                            this.wheatinformation.push(e)
                            // this.ChatNav[0].OnlineNmuver =this.wheatinformation.length
                        }
                    })
                    this.Gethears(res.data)
                }                     
            }).catch((error) =>{
                console.log(error)
            })
        },
        Gethears(data){
            /**
                * enterPushers：新进推流人员信息
                * leavePushers：退出推流人员信息
                * ishave：用于判断去重操作
            */
            var _this = this
            var enterPushers = [],leavePushers = [],ishave = 0;
            data.pushers.forEach(function(val1){  
                ishave = 0;
                _this.RoomInfoos.pushers.forEach(function(val2){
                    if(val1.userID == val2.userID){
                        ishave = 1;
                    }
                });
                if(!ishave && val1.userID != _this.unserinfo.user_id){
                    enterPushers.push(val1);
		            ishave = 0;
                }
            })
            _this.RoomInfoos.pushers.forEach(function(val1){
                ishave = 0;
                data.pushers.forEach(function(val2){
                    if(val1.userID == val2.userID) {
			            ishave = 1;
		            }
                });
                if(!ishave){
                    leavePushers.push(val1);
                    ishave = 0;
                };
            })
            _this.RoomInfoos.pushers = data.pushers;
            if(enterPushers.length) {
                console.log( this.wheatinformation,'???')
                enterPushers.forEach(e=>{
                     console.log(e,'==>')
                    var streamID = _this.getStreamIDByStreamUrl(e.accelerateURL);
                    e.Id = streamID
                    _this.roomdis.push(e)
                    console.log(_this.roomdis,'==>')
                    if(e.userID != _this.unserinfo.user_id){
                        var url ="http://live.curiousmore.com/live/"+streamID+'.m3u8'
                        setTimeout(function () {//延迟2s执行IM的获取消息等功能防止sdk报错
                           var player = new TcPlayer(streamID, {
                                m3u8: url,
                                autoplay:true,
                                width:'80',
                                height:'140',
                                controls:'none' ,
                            }); 
                        },1000);
                              
                    }
                })
                this.mergeStream(1);
            }
            // 通知有人退出房间
            if(leavePushers.length) {
                console.log('退房:', JSON.stringify(leavePushers));
                leavePushers.forEach(e=>{
                    var streamID = _this.getStreamIDByStreamUrl(e.accelerateURL);
                    e.Id = streamID
                    _this.roomdis.push(e)
                    var ids = '.'+streamID
                    $('.videsu').remove();
                })
               this.mergeStream(1)
            }
        },
        getStreamIDByStreamUrl(streamUrl){//截取房间id
            if (!streamUrl) {
                return null;
            }
            var subStr = streamUrl;
            var index = subStr.indexOf('?');
            if (index >= 0) {
                subStr = subStr.substring(0, index);
            }
            if (!subStr) {
                return null;
            }
            index = subStr.lastIndexOf('/');
            if (index >= 0) {
                subStr = subStr.substring(index + 1);
            }
            if (!subStr) {
                return null;
            }
            index = subStr.indexOf('.');
            if (index >= 0) {
                subStr = subStr.substring(0, index);
            }
            if (!subStr) {
                return null;
            }
            return subStr;
        },
        mergeStream(retryCount){//混流
            var _this = this
            var mergeStreams = [];
            if(_this.RoomInfoos.pushers.length > 0) {
                _this.RoomInfoos.pushers.forEach(function (val) {
                    if (val.userID != _this.RoomInfoos.roomCreator) {//获取流id
                        var streamID = _this.getStreamIDByStreamUrl(val.accelerateURL);
                        if (streamID) {
                            mergeStreams.push({
                                userID: val.userID,
                                streamID: streamID,
                                width: val.width,
                                height: val.height
                            });
                        }
                    } else {
                        _this.bigAnchorStreamID = _this.getStreamIDByStreamUrl(val.accelerateURL);
                    }
                });
	        }
            _this.sendStreamMergeRequest(retryCount, mergeStreams);
        },
        sendStreamMergeRequest(retryCount, mergeStreams) {//开始混流
            var _this = this
            if (retryCount < 0) {
                return;
            }
            var mergeInfo = this.createMergeInfos(mergeStreams);
            console.log('混流信息:', JSON.stringify(mergeInfo));
            this.doMergeRequest(mergeInfo, function (ret) {
                if (ret) {
                    console.log('混流成ssss功');                   
                } else {
                    console.log('混流失败9999');
                    setTimeout(() => {
                        retryCount--;
                        this.sendStreamMergeRequest(retryCount, mergeStreams);
                    }, 2000);
                }
            });
        },
        createMergeInfos(mergeStreams) {//创建混流信息
            var _this = this
            console.log("混流原始信息:", JSON.stringify(mergeStreams));
            var smallAnchorWidth = 270;
            var smallAnchorHeight = 270;
            var bigAnchorWidth = 1920;
            var bigAnchorHeight = 1080;
            var offsetHeight = 0;
            // if (bigAnchorWidth < 540 || bigAnchorHeight < 960) {
            //     smallAnchorWidth = 32;
            //     smallAnchorHeight = 32;
            //     offsetHeight = 0;
            // }
            //组装混流JSON结构体
            var streamInfoArray = [];
            if (mergeStreams && mergeStreams.length > 0) {
                var bigAnchorInfoCanvas = {
                input_stream_id: _this.bigAnchorStreamID || '',
                    layout_params: {
                        image_layer: 1,
                        image_width:bigAnchorWidth,
                        image_height: bigAnchorHeight,
                        input_type: 3,
                        color: '0xFFFFFF',
                        location_x: subLocationX,
				        location_y: subLocationY - layerIndex * smallAnchorHeight
                    }
                }
                var bigAnchorInfo = {//大主播
                    input_stream_id: _this.bigAnchorStreamID,
                    layout_params: {
                        image_layer: 2,
                        image_width: bigAnchorWidth,
                        image_height: bigAnchorHeight,
                        location_x: subLocationX,
				        location_y: subLocationY - layerIndex * smallAnchorHeight
                    }
            }
            streamInfoArray.push(bigAnchorInfoCanvas)
            streamInfoArray.push(bigAnchorInfo);
            //小主播
            var subLocationX = bigAnchorWidth - smallAnchorWidth;
            var subLocationY = bigAnchorHeight - smallAnchorHeight - offsetHeight;
            if (mergeStreams && mergeStreams.length > 0) {
                var layerIndex = 0
                var layerIndexs = 3
                mergeStreams.forEach(function (val) {
                    var smallAchorInfo = {//组装JSON
                        input_stream_id: val.streamID,
                        layout_params: {
                            image_layer: layerIndex + 3,
                            image_width: smallAnchorWidth,
                            image_height: smallAnchorHeight,
                            location_x: subLocationX,
                            location_y: subLocationY - layerIndexs * smallAnchorHeight,
                        }   
                    }
				    streamInfoArray.push(smallAchorInfo);
                    layerIndex++;
                    layerIndexs--;
                });
            }
            } else {
                var bigAnchorInfo = {
                    input_stream_id: _this.bigAnchorStreamID || '',
                    layout_params: {
                        image_layer: 1,
                        image_width: 1920,
				        image_height: 1080,
                    }
                }
                streamInfoArray.push(bigAnchorInfo);
            }
            var para = {
                app_id: '1400255047',
                interface: 'mix_streamv2.start_mix_stream_advanced',
                mix_stream_session_id: _this.bigAnchorStreamID,
                output_stream_id: _this.bigAnchorStreamID,
                input_stream_list: streamInfoArray
            }
            console.log(para.input_stream_list,'000')
            var interfaceObj = {
                interfaceName: 'Mix_StreamV2',
                para: para
            }
            var reqParam = {
                timestamp: Math.round((Date.now() / 1000)),
                eventId: Math.round((Date.now() / 1000)),
                interface: interfaceObj
            }
            return reqParam;
        },
        doMergeRequest(mergeInfo, callback){//混流开始
            var data = {
                userID:this.unserinfo.user_id,
                roomID:this.RoomInfoos.roomID,
                mergeParams:JSON.stringify(mergeInfo),
                token:localStorage.getItem('token')
            }
            this.$axios({
                method:'post',
                url:'https://liveroom.qcloud.com/weapp/live_room/merge_stream',
                params:data,
                data: data,
            }).then((res) =>{
                console.log(res.data,'连线成功')
               if (res.data.merge_msg == "Success!") {
                    console.log('1')
                    callback(true);
                }else{
                    console.log('2')
                    console.error('混流失败:',res.data);
                    callback(false);
                    return;
                }
            }).catch((error) =>{
                console.log(error)
            })
        },

        //待上麦的删除
        todelete(e){
            console.log(e)
            this.wheatlist.splice(e,1)
            // this.ChatNav[1].OnlineNmuver--
        },
        Placedtop(top,index){//待上麦置顶功能
            this.wheatlist.splice(index,1)
            this.wheatlist.unshift(top)
        },
        invitationwheet(e,index){//邀请连麦
            var _this = this
            console.log(e,'=><')
            var mTimeDiff = 0;
            var data ={
				cmd:"linkmicinvtier",
				data:{
					Invateindex:'',
					roomID:_this.group_ids,
					type:'request',
					timestamp: Math.round(Date.now()) - mTimeDiff,
					userAvatar: _this.unserinfo.avatar,
					userID:_this.unserinfo.user_id,
					userName:_this.unserinfo.nick_name
				}
            }
            let message = _this.tim.createCustomMessage({
                to: e.userID,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    data:JSON.stringify(data),
                    description: '',
				    extension: '',
                }
            });
            let promise = _this.tim.sendMessage(message);
            promise.then(function(imResponse) {// 发送成功
                console.log("邀请成功")
                _this.wheatlist.splice(index,1)
                // _this.ChatNav[1].OnlineNmuver--
            }).catch(function(imError) {//发送失败
                console.log(imError,'发送失败')
            });
        },
        invitationwheets(e){
            var _this = this
            var mTimeDiff = 0;
            var data ={
				cmd:"linkmicinvtier",
				data:{
					Invateindex:'',
					roomID:_this.group_ids,
					type:'request',
					timestamp: Math.round(Date.now()) - mTimeDiff,
					userAvatar: _this.unserinfo.avatar,
					userID:_this.unserinfo.user_id,
					userName:_this.unserinfo.nick_name
				}
            }
            console.log(data,'=><')
            let message = _this.tim.createCustomMessage({
                to:JSON.stringify(e.user_id),
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    data:JSON.stringify(data),
                    description: '',
				    extension: '',
                }
            });
            let promise = _this.tim.sendMessage(message);
            promise.then(function(imResponse) {// 发送成功
                console.log("邀请成功")
            }).catch(function(imError) {//发送失败
                console.log(imError,'发送失败')
            });
        },
        kicking(e){//连麦成功后踢人下麦
            var _this = this
            var mTimeDiff = 0;
            var data ={
				cmd:"linkmic",
				data:{
					Invateindex:'',
					roomID:_this.group_ids,
					type:'kickout',
					timestamp: Math.round(Date.now()) - mTimeDiff,
					userAvatar: _this.unserinfo.avatar,
					userID:_this.unserinfo.user_id,
					userName:_this.unserinfo.nick_name
				}
            }
            let message = _this.tim.createCustomMessage({
                to: e.userID,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    data:JSON.stringify(data),
                    description: '',
				    extension: '',
                }
            });
            let promise = _this.tim.sendMessage(message);
            promise.then(function(imResponse) {// 发送成功
                console.log("成功")
            }).catch(function(imError) {//发送失败
                console.log(imError,'发送失败')
            });
        }
    },
    components: {//组件注册
        Footer,
        Head,
        Modal
    },
}
</script>
<style lang="less" scoped>
    .LivevideoRoom{
        width: 100%;
        height: auto;
    }
    .LivevideoRoom-con{
        position: relative;
        min-width: 1400px;
        width: 100%;
        background:rgba(241,241,241,1);
        height: 1000px;
        padding-top: 60px;
    }
    .LivevideoRoom-content{
        position: relative;
        width: 1400px;
        height: 750px;
        margin: 0 auto;
        background:rgba(43,53,71,1);
        border-radius:15px;
        margin-bottom: 200px;
    }
    .LivevideoRoom-content>div{
        position: relative;
        width: 96%;
        margin: 0 auto;
        display: flex;
        justify-content: center;
    }
    .LivevideoRoom-head{
        position: relative;
        width: 100%;
        height: 100px;
        display: flex;
    }
    .head-left{
        width: 50%;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        label{
            width: 100%;
            &:first-child{
                color: #29E1E2;
                font-weight: bold;
                font-size: 24px;
            }
            &:last-child{
                color: #C4CEE1;
                font-size: 16px;
                span{
                    display: inline-block;
                    width: 16%;
                }
            }
        }
    }
    .head-right{
        width: 50%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        label{
            width: 30%;
            text-align: right   ;
            span{
                color: #BDC8DB;
                font-size: 16px;
            }
            &:first-child{
                span{
                    color: #BDC8DB;
                    font-size: 18px;
                    display: inline-block;
                    height: 40px;
                    line-height: 40px;
                    // padding-left: 4%;
                    background-image: url('/images/圆角矩形 30@2x.png');
                    background-repeat: no-repeat;
                    background-size: 27px 30px;
                    width: 100%;
                 }
            }
            &:last-child{
                span{
                    display: inline-block;
                    width: 144px;
                    height: 40px;
                    border:1px solid rgba(71,206,207,1);
                    border-radius:20px;
                    text-align: center;
                    line-height: 40px;
                    color: #29E1E2;
                    font-size: 14px!important;
                    cursor: pointer;
                }
            }
        }
    }
    .LivevideoRoom-left{
        width: 1000px;
        height: 613px;
    }


    //直播间信息
    #video_test{
        width: 100%;
        height: 553px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    #video_test>span{
        display: inline-block;
        font-size: 20px;
        text-align: center;
        cursor: pointer;
        color: #ffffff;
        width: 230px;
        height: 40px;
        line-height: 40px;
        // line-height: 553px;
        border-radius: 20px;
        border: 1px solid #eeeeee;
    }
    .video-footer{
        display: flex;
        width: 100%;
        align-items: center;
        justify-content: flex-end;
        height: 60px;
        background:rgba(31,39,55,1);
        img{
            margin-right: 4%;
            &:nth-child(1){
                width: 13px;
                height: 20px;
            }
            &:nth-child(2){
                width: 19px;
                height: 18px;
            }
        }
        span{
            display: inline-block;
            width: 31px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            margin-right: 40px;
            background:rgba(255,255,255,1);
            border-radius:9px;
            font-size: 12px;
            color: #2B3547;
        }
    }



    //直播间样式
    .LivevideoRoom-right{
        width: 333px;
        height: 613px;
        margin-left: auto;
    }
    .oicebroadcast-info-right{
         span{
           display: inline-block;
           display: inline-block;
            width: 30%;
            height: 40px;
            line-height: 40px;
            border:1px solid rgba(71,206,207,1);
            border-radius: 20px;
            text-align: center;
            cursor: pointer;
            color: #29E1E2;
            font-size: 14px;
            background-image: url('/images/组 14@2x.png');
            background-repeat: no-repeat;
            background-position-x: 90%;
            background-position-y: 50%;
            background-size: 19px 17px;
        }   
    }
    .LivevideoRoom-right-head{
        position: relative;
        width: 100%;
        height: 180px;
        background:rgba(31,39,55,1);
    }
    .LivevideoRoom-right-head>ul{
        list-style: none;
        padding: 0;
        margin: 0;
        display: flex;
        width: 100%;
        height: 36px;
        background:rgba(46,65,97,1);
        align-items: center;
        justify-content: center;
        li{
            width: 33.3%;
            color: #FFFFFF;
            font-size: 12px;
            height: 36px;
            line-height: 36px;
            text-align: center;
            cursor: pointer;
        }
    }
    .LivevideoRoom-right-head-lsit{
        position: relative;
        width: 100%;
        height: 120px;
        margin: 0 auto;
        overflow: visible;
    }
    // .LivevideoRoom-right-head-lsit>div{
    //     background: #1f2737;
    //     height: 400px;
    //     z-index: 10000;
    // }
    .LivevideoRoom-right-head-lsit>div>ul{
        padding: 0;
        list-style: none;
        background: #1f2737;
        height: 400px;
        z-index: 2;
        flex-wrap: wrap;
        li{
            width: 100%;
            display: flex;
            align-items: center;
            margin-top: 10px;
        }
    }
    .LivevideoRoom-right-head-lsit>div>ul>li>label{
        display: flex;
        width: 50%;
        align-items: center;
        img{
            width: 26.9px;
            height: 26.5px;
            border-radius: 20px;
        }
        &:first-child{
            span{
                color: #FFFFFF;
                font-size: 12px;
                display: inline-block;
                width: 70%;
                margin-left: 4%;
            }
        }
        &:last-child{
            text-align: right;
            span{
                display: inline-block;
                width: 100%;
                text-align: right;
                color: #33CCCD;
                font-size: 12px;
                cursor: pointer;
            }
        }
    }
    // .navsed{
    //     background:rgba(31,39,55,1);
    // }
    .LivevideoRoom-right-content{
        position: relative;
        width: 100%;
        height: 433px;
        background:rgba(31,39,55,0.7);
    }
    .Systemmessage{
        position: relative;
        width: 90%;
        margin: 0 auto;
        p{
            color: #2DC7C8;
            font-size: 12px;
            margin: 0 auto;
            padding-top: 10px;
            &:last-child{
                line-height: 20px;
                letter-spacing: 4px;
            }
        }
    }
    .MessageList{
        position: relative;
        width: 90%;
        height: 55%;
        margin: 0 auto;
        padding: 0;
        overflow: auto;
    }
    .MessageList>ul{
        position: relative;
        width: 90%;
        margin: 0 auto;
        padding: 0;
        list-style: none;
        li{
            height: 30px;
            line-height: 30px;
            width: 100%;
            span{
                font-size: 12px;
                &:first-child{
                    color: #2DC7C8;
                }
                &:last-child{
                    color: #FFFFFF;
                    margin-left: 4%;
                }
            }
        }
    }
    .MessageList::-webkit-scrollbar,.nas1::-webkit-scrollbar{
        width:6px!important;
        background: #eeeeee;
    }
    .MessageList::-webkit-scrollbar-thumb,.nas1::-webkit-scrollbar-thumb{
         background: #aaa;
         height: 24px!important;
         width: 24px;
         border-radius:10px;
    }
    .messagefooter{
        position: relative;
        width: 100%;
        margin: 0 auto;
        height: 50px;
        background:rgba(255,255,255,1);
        position: absolute;
        right: 0px;
        bottom: 10px;
    }
    .messagefooter>label{
        display: inline-block;
        width: 100%;
        height: 20%;
    }
    .messagefooter>div{
        display: flex;
        height: 70%;
    }
    .messagefooter>div>textarea{
        display: inline-block;
        border: none;
        height: 100%;
        width: 80%;
        outline: none;
        resize: none;
        overflow:hidden;
        padding-left: 4%;
        margin-top: -10px;
    }
    .messagefooter>div>span{
        display: inline-block;
        width: 54px;
        height: 30px;
        text-align: center;
        background: #2B3547;
        border-radius: 10px;
        line-height: 30px;
        cursor: pointer;
        color: #ffffff;
        font-size: 12px;
    }

    //在线人数样式
    .onlineitem{
        position: relative;
        width: 90%;
        margin: 0 auto;
        padding: 0;
        list-style: none;
        background: #1f2737;
        height: 400px;
        z-index: 2;
        flex-wrap: wrap;
        li{
            width: 100%;
            display: flex;
            align-items: center;
            margin-top: 10px;
        }
    }
    .onlineitem>li>label{
        display: flex;
        width: 50%;
        align-items: center;
        img{
            width: 26.9px;
            height: 26.5px;
            border-radius: 20px;
        }
        &:first-child{
            span{
                color: #FFFFFF;
                font-size: 12px;
                display: inline-block;
                width: 70%;
                margin-left: 4%;
            }
        }
        
    }
    .onlineitem>li>label>label{
        width: 100%;
        display: flex;

    }
    .online{
        span{
            display: inline-block;
            width: 100%;
            text-align: right;
            font-size: 12px;
            cursor: pointer;
            &:first-child{
                color: #ffffff; 
            }
            &:last-child{   
                color: #33CCCD;
            }
        }
    }
    .outline{
        span{
            display: inline-block;
            width: 100%;
            text-align: right;
            font-size: 12px;
            cursor: pointer;
            color: rgb(154, 154, 154);
        }
    }
    .classinfos{
        position: absolute;
        width: 332px;
        height: 200px;
        background:rgba(255,255,255,1);
        top: 100px;
        right:-20px;
        z-index: 10;
    }
    .classinfos>div{
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 20px;
        &:last-child{
            label{
                img{
                    width: 36px;
                    height: 36px;
                }
            }
        }
    }
    .classinfos>div>label{
        width: 33%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-wrap: wrap;
        span{
            display: inline-block;
            width: 100%;
            text-align: center;
            font-size: 12px;
        }
    }
    .classinfos>div>label>img{
        width: 27px;
        height: 30px;
    }
    .classinfos-avater{
        img{
            width: 55px!important;
            height: 55px!important;
            margin-top: -140px;
            border-radius: 30px;
        }
        span{
            color: #141D2D!important;
            font-weight: Bold;
            font-size: 16px!important;
        }
    }
    .iconfos{
        display: inline-block;
        width: 40px;
        height: 40px;
        background: #ffffff;
        margin-left: 4%;
        margin-top: -5px;
        transform:rotate(30deg);
    }

    //展开样式
    .nas1{
        width: 100%;
        height: 120px;
        // border-bottom: 1px solid #eee;
        background: #1f2737;
        z-index: 2;
        position: absolute;
    }
    .nas2{
        overflow: hidden;
        padding: 0px;
        max-height: 320px;
    }
    .nas2{
        height: 320px;
        overflow: hidden;
        position: relative;
    }


    //待麦样式
    .Tomak>li>label{
        &:last-child{
            height: 27px;
            width: 50%;
            display: flex;
            justify-content: flex-end;
            img{
                margin-left: 12%;
                width: 17px;
                height: 17px;
                cursor: pointer;
                &:last-child{
                    width: 12px;
                    height: 13px;
                }
            }
        }
    }
    .Nodata{
        position: relative;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-wrap: wrap;
        height: 140px;
        img{
            width: 50px;
        }
        span{
            display: inline-block;
            width: 100%;
            text-align: center;
        }
    }
    .videolist{
        position: absolute!important;
        right:27%;
        top: 13.5%;
        width: 140px!important;
        display: flex;
        flex-wrap: wrap;
        height: 553px;
        overflow: hidden;
    }
    .videsu{
        // margin-top: 20px;
        width: 80px;
        height: 140px;
    }
</style>